package com.vagavaga.tx;

import java.util.HashMap;

import javax.sql.DataSource;

final class DataSourceRegistry {
    private static final DataSourceRegistry instance = new DataSourceRegistry();
    
    public static DataSourceRegistry instance() {
        return instance;
    }
    
    private HashMap<String, DataSource> registry = new HashMap<String, DataSource>();
    private HashMap<DataSource, String> rreg     = new HashMap<DataSource, String>();
    
    public DataSource put(DataSource ds) {
        return put("", ds);
    }
    public DataSource put(String name, DataSource ds) {
        if (name == null) throw new IllegalArgumentException("name must be given");
        if (ds == null) throw new IllegalArgumentException("datasource must be given");
        synchronized (registry) {
            DataSource source = registry.get(name);
            if (source == null) {
                source = ds;
                registry.put(name, ds);
                rreg.put(ds, name);
            }
            
            return source;
        }
    }
    
    public DataSource get(String name) {
        synchronized (registry) {
            return registry.get(name);
        }
    }
    
    public String get(DataSource ds) {
        synchronized(registry) {
            return rreg.get(ds);
        }
    }
    
    public DataSource unbind(String name) {
        if (name == null) throw new IllegalArgumentException("name must be given");
        synchronized (registry) {
            DataSource ds = registry.remove(name);
            if (ds != null) rreg.remove(ds);
            return ds;
        }
    }
}
